package com.zing.controller.common;

import com.zing.constant.MessageConstant;
import com.zing.result.Result;
import com.zing.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags="通用接口")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    // 文件上传
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("上传文件名: {}", file.getName());

        //原始文件
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null) {
            String extionsion = originalFilename.substring(originalFilename.lastIndexOf(".")); //后缀

            //文件上传阿里云
            String fileName = UUID.randomUUID() + extionsion;
            try {
               String filePath = aliOssUtil.upload(file.getBytes(), fileName);
               return Result.success(filePath);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
